/*
 * File Name：WordReadActivity.java
 * Copyright：Copyright 2008-2014 CiWong.Inc. All Rights Reserved.
 * Description：WordReadActivity.java
 * Modify By：jejun
 * Modify Date：2014-2-10
 * Modify Type：Add
 */
package com.ciwong.epaper.modules.evaluate.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.common.guidedialog.BaseGuideLayerDialog;
import com.ciwong.epaper.common.guidedialog.CountDownDialog;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.IntensiveReadingResultBean;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.bean.WorkAnswers;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.RepeatKeyUtil;
import com.ciwong.epaper.modules.evaluate.bean.AnswerRecorder;
import com.ciwong.epaper.modules.evaluate.bean.RepeatAnswerInfo;
import com.ciwong.epaper.modules.evaluate.bean.Sentence;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.evaluate.util.UnitSpeechControler;
import com.ciwong.epaper.modules.evaluate.util.UnitSpeechControler.OnShowFirstRecordTipListener;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.EJumpManager;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.ScoreUtils;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.widget.IntensiveReadingDialog;
import com.ciwong.epaper.widget.PlayStateView;
import com.ciwong.epaper.widget.evaluate.UnitSpeechView;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.audio.play.OnPlayListener;
import com.ciwong.libs.oralevaluate.bean.EvaluateResult;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.utils.ImageLoaderHelper;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.CWDialog;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.unisound.edu.oraleval.sdk.sep15.IOralEvalSDK;
import com.unisound.edu.oraleval.sdk.sep15.OralEvalSDKFactory;
import com.unisound.edu.oraleval.sdk.sep15.SDKError;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 单词跟读界面
 *
 * @author jejun
 * @version ciwong v.1.0 2014-2-10
 * @since ciwong v.1.0
 */
public class WordReadActivity extends BaseSpeechActivity implements
        UnitSpeechControler.OnSpeechListener, CountDownDialog.CountInterFace,
        IntensiveReadingDialog.IntensiveReadingClickListener {
    private UnitSpeechView unitSpeech;

    private TextView scoreView;

    boolean isShowHelp;


    public static final int CODE_REQUEST_RECORD_AUDIO_PERMISSION = 8801;

    protected CountDownDialog countDownDialog;

    // 学习记录相关
    private RelativeLayout studentRel;

    private Handler mHandler = new Handler();

    private View recordTipView;

    public long audioDuration = 3500;// 单词播放时长

    private TextView completion_text;
    private TextView see_work_score_text;
    private TextView smooth_text;
    private TextView accuracy_text;


    @Override
    protected int setView() {
        return R.layout.word_read;
    }

    @Override
    protected void preCreate() {
        super.preCreate();

        showCricleProgress();// 显示全屏进度条

    }

    @Override
    protected void findViews() {
        super.findViews();
        unitSpeech = findViewById(R.id.unitSpeech);
        scoreView = findViewById(R.id.tv_show_score);
        completion_text = findViewById(R.id.completion_text);
        see_work_score_text = findViewById(R.id.see_work_score_text);
        smooth_text = findViewById(R.id.smooth_text);
        accuracy_text = findViewById(R.id.accuracy_text);
        // 记录相关
        studentRel = findViewById(R.id.student_jilu);
        View finishRecordView = read_bottom_view.getFinishRecordView();
        recordTipView = read_bottom_view.getRecordTipView();
        if (finishRecordView != null)
            finishRecordView.setOnClickListener(new View.OnClickListener() {// 点击提前完成录音
                @Override
                public void onClick(View v) {
                    if (speechControler != null) {
                        speechControler.complateRecord();
                    }
                }
            });

    }

    @Override
    protected void init() {
        super.init();
        TAG = "retryscore2";

        try {
            isShowHelp = CWSys
                    .getSharedBoolean(EConstants.SHARE_KEY_REPEAT_READ_HELP_TIP
                            + getUserInfoBase().getUserId(), true);
            if (isShowHelp) {
                final BaseGuideLayerDialog dialog = new BaseGuideLayerDialog(
                        this, R.style.DialogStyleGuide);
                dialog.setContentView(R.layout.dialog_repeat_read_tip);
                dialog.setCancelable(false);
                View btIKnow = dialog.findViewById(R.id.tv_know);
                View tvPersualKnow = dialog.findViewById(R.id.tx_perusal_know);
                final View rlWordPersualColor = dialog
                        .findViewById(R.id.rl_word_perusal_color);
                final View rlWordPersualStyle = dialog
                        .findViewById(R.id.rl_word_perusal_style);

                btIKnow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        rlWordPersualColor.setVisibility(View.GONE);
                        dialog.dismiss();
                        //rlWordPersualStyle.setVisibility(View.VISIBLE);
                    }
                });
                tvPersualKnow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();

                    }
                });

                dialog.setOnDismissListener(
                        new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog1) {
                                isShowHelp = false;
                                loadData();
                                CWSys.setSharedBoolean(
                                        EConstants.SHARE_KEY_REPEAT_READ_HELP_TIP
                                                + getUserInfoBase().getUserId(),
                                        false);
                            }
                        });
                dialog.show();
            }

            if (mWorkContents != null) {
                setTitleText(mWorkContents.getResourceName());
            } else {
                setTitleText(mResourceName);
            }
            setGoBackListener(new GoBackListener() {
                @Override
                public void goBack() {
                    WordReadActivity.this.goBack();
                }
            });
        } catch (Exception e) {
            e.getStackTrace();
        }
        // 设置评分系数
        ScoreUtils.setSocreCoefficient();
        String text = "查看分数";
        SpannableString spannableString = new SpannableString(text);
        spannableString.setSpan(new UnderlineSpan(), 0, text.length(), 0);
        see_work_score_text.setText(spannableString);
        see_work_score_text.setOnClickListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                setBuyServiceDialog();
            }
        });
    }

    /**
     * 第一次显示完成录音给的提示
     */
    private void showFirstRecord(final View recordTipView, long addDuation) {

        boolean isShow = CWSys
                .getSharedBoolean(EConstants.SHARE_KEY_SHOW_FINISH_RECORD_TIP
                        + getUserInfoBase().getUserId(), true);
        CWLog.d("提示：", isShow + "");
        if (isShow) {
            if (recordTipView == null)
                return;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    recordTipView.setVisibility(View.VISIBLE);
                }
            }, addDuation);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    recordTipView.setVisibility(View.GONE);
                }
            }, addDuation + 1500);
            CWSys.setSharedBoolean(EConstants.SHARE_KEY_SHOW_FINISH_RECORD_TIP
                    + getUserInfoBase().getUserId(), false);
        }
    }

    /**
     * 初始化评测库
     */
    private void initYzs() {
        speechControler = new UnitSpeechControler(WordReadActivity.this,
                unitSpeech, startDate, serviceExpired);
        speechControler.setOnShowFirstRecordTipListener(
                new OnShowFirstRecordTipListener() {
                    @Override
                    public void onShowFirstRecordTip(long addDuation) {
                        // showFirstRecord(recordTipView, addDuation);
                    }
                });
    }

    /**
     * 初始化数据
     */
    private void initData(String saveUUid) {
        if (!ImageLoader.getInstance().isInited()) {
            ImageLoaderHelper.getInstance().init(getApplicationContext());
        }
        if (isRepeatWord) {// 重新跟读
            speechControler.setUnitText(null);
            speechControler.setRequContent(null);
        } else {
            speechControler.setUnitText(mVersionId);
            speechControler.setRequContent(requirementContent);
        }
        speechControler.setReadMode(readMode);
        speechControler.setPlayAssess(isPlayAssess);
        speechControler.setUnitWord(words, read_bottom_view, scoreView, see_work_score_text, completion_text, smooth_text, accuracy_text,
                saveUUid, getUserInfoBase().getUserId(), isRepeatWord);
        speechControler.setOnUnitSpeechListener(this);
        speechControler.setRepeatDuration(1000);
        speechControler.setReadDuration(1000);

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (speechControler != null) {
            speechControler.setPlayAssess(isPlayAssess);
        }
        if (speechControler.isPause() && isLearn
                && !isIntensiveReadingDialogShowing()) {
            playOrPause(true, false);
        }

    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    public void goBack() {
        //
        if (isRepeatWord) {// 重新跟读
            finish();
        } else {
            if (isLearn) {
                showDailog();
            } else {
                finish();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isLearn) {
            if (!speechControler.isPause()) {
                cancelTimer();
                pause();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelTimer();
        hideIntensiveReadingDialog();
        if (speechControler != null) {
            speechControler.stop();
            speechControler.release();
        }
    }

    @Override
    protected void loadData() {
        try {
            initYzs();
            if (isRepeatWord) {// 重读逻辑
                hideCricleProgress();
                if (TextUtils.isEmpty(mUuid)) {
                    return;
                }
                initData(mUuid);
                speechControler.currentListenAndRepeatIndex = 0;
                refreshWordUi(0);
                playOrPause(false, false);

            } else {
                String uuidkey = RepeatKeyUtil.getWordUuidSaveKey(mDownLoadInfo,
                        mModule, position, intentWorkId, readMode);
                final String saveUUid = CWSys.getSharedString(uuidkey, null);

                Log.d(TAG, "#######uuidkey#########" + uuidkey);

                if (null != saveUUid) {
                    Log.d(TAG, "#######null != saveUUid saveUUid#########"
                            + saveUUid);
                    mUuid = saveUUid;
                    startDate = CWSys.getSharedLong(getStartTime(),
                            System.currentTimeMillis());
                    workLong = (int) (System.currentTimeMillis() - startDate)
                            / 1000;
                    int oldWorkLong = CWSys.getSharedInt(getSaveTime(), 0);
                    if (workLong < oldWorkLong || workLong < 0) {
                        workLong = oldWorkLong;
                    }
                } else {
                    Log.d(TAG, "#######mUuid#########" + mUuid);
                    CWSys.setSharedString(uuidkey, mUuid);
                    CWSys.setSharedLong(getStartTime(), startDate);
                }

                ///
                if (EConstants.IS_YOUKE && EConstants.WORD_IS_YOUKE_LOGIN) {
                    EConstants.WORD_IS_YOUKE_LOGIN = false;
                    FileUtils.delete(ESystem.getAnswersUuidPath(saveUUid));
                    clearRecord();
                    speechControler.currentListenAndRepeatIndex = 0;
                    loadWordDetails(mUuid, 0);
                } else {
                    EConstants.WORD_IS_YOUKE_LOGIN = false;
                    getSaveDoWorkRecord(new BaseExtCallBack(
                            WordReadActivity.this, EApplication.getInstance()
                            .getUserInfoBase().getUserId() + "") {
                        @Override
                        public void success(Object data) {
                            try {
                                ArrayList<AnswerRecorder> tempList;
                                if (data instanceof CopyOnWriteArrayList) {
                                    tempList = new ArrayList<AnswerRecorder>();
                                    if (null != data) {
                                        tempList.addAll(
                                                (ArrayList<AnswerRecorder>) data);
                                    }

                                } else {
                                    tempList = (ArrayList<AnswerRecorder>) data;
                                }

                                if (tempList != null) {
                                    speechControler.answerRecorders = tempList;
                                }
                            } catch (Exception e) {
                                e.getStackTrace();
                            }

                            getSaveUserAnswerRecord(saveUUid);
                        }

                        @Override
                        public void failed(int errorCode, Object data) {
                            failed(data);
                        }

                        @Override
                        public void failed(Object data) {
                            // 做作业记录保存失败，答案记录也应该作废，否则不同步就会出现零分问题--neo 2016/10/28
                            // getSaveUserAnswerRecord(saveUUid);
                            // String saveUuid =
                            // CWSys.getSharedString(RepeatKeyUtil.getUuidSaveKey(mDownLoadInfo,
                            // mModule, position, intentWorkId,readMode));
                            Log.d(TAG,
                                    "#######getSaveDoWorkRecord  failed#########"
                                            + mUuid);
                            FileUtils.delete(
                                    ESystem.getAnswersUuidPath(saveUUid));
                            clearRecord();
                            speechControler.currentListenAndRepeatIndex = 0;
                            loadWordDetails(mUuid, 0);
                        }

                    }, saveUUid);
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
        }

    }

    /**
     * 获取保存的用户答案记录
     */
    private void getSaveUserAnswerRecord(final String saveUUid) {
        Log.d(TAG,
                "#######getSaveUserAnswerRecord  saveUUid#########" + saveUUid);
        getSaveUserAnswerList(new BaseExtCallBack(WordReadActivity.this) {
            @Override
            public void success(Object data) {
                // 继续学习按钮回调

                Log.d(TAG, "#######getSaveUserAnswerRecord  success#########"
                        + mUuid);
                ArrayList<WorkAnswers<RepeatAnswerInfo>> saveAnswersList;
                saveAnswersList = (ArrayList<WorkAnswers<RepeatAnswerInfo>>) data;
                int currPoint = 0;
                if (saveAnswersList != null) {
                    speechControler.userAnswerseList = saveAnswersList;
                    currPoint = saveAnswersList.size();
                    speechControler.currentListenAndRepeatIndex = currPoint;
                }
                loadWordDetails(mUuid, currPoint);
            }

            @Override
            public void failed(int errorCode, Object data) {
                failed(data);
            }

            @Override
            public void failed(Object data) {
                // 做作业记录保存失败，答案记录也应该作废，否则不同步就会出现零分问题--neo 2016/10/28
                // String saveUuid = CWSys.getSharedString(getUuidSaveKey());

                Log.d(TAG, "#######getSaveUserAnswerRecord  failed#########"
                        + mUuid);

                speechControler.userAnswerseList = new ArrayList<WorkAnswers<RepeatAnswerInfo>>();
                speechControler.answerRecorders = new ArrayList<AnswerRecorder>();

                FileUtils.delete(ESystem.getAnswersUuidPath(saveUUid));
                clearRecord();
                speechControler.currentListenAndRepeatIndex = 0;
                loadWordDetails(mUuid, 0);
            }
        }, speechControler.answerRecorders, saveUUid);
    }

    /**
     * 退出做作业提示框
     */
    private void showDailog() {
        if (!speechControler.isPause()) {
            playOrPause(true, false);
            UnitSpeechControler.readCount--;
        }
        CWDialog mDialog = new CWDialog(this);
        // mDialog.setTitle(R.string.lear_title);
        mDialog.setMessage(R.string.confirm_back_work);
        mDialog.setPositiveButton(android.R.string.cancel,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (mIsUnAutoMode && speechControler != null
                                && speechControler.isPause() && isLearn
                                && !isIntensiveReadingDialogShowing()) {
                            playOrPause(true, false);
                        }
                    }
                });
        mDialog.setNegativeButton(R.string.ok,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        // 缓存同步再退出
                        UnitSpeechControler.readCount = 0;
                        dialog.dismiss();

                        showCricleProgress("正在保存记录！");
                        checkCachDataSync();
                        // AudioPlayer.getInstance().stop();
                        // FileUtils.delete(NSystem.getAnswersMediaPath(uuid));
                        // finish();
                    }
                });
        // }
        mDialog.show();
    }

    private void checkCachDataSync() {

        String keyDoWork = RepeatKeyUtil.getWordRepeatRecordListKey(
                mDownLoadInfo, mModule, position, intentWorkId, mUuid);
        SerializableManager.getInstance().deSerialize(keyDoWork,
                new BaseCallBack() {
                    @Override
                    public void success(Object data) {
                        try {
                            final ArrayList<AnswerRecorder> tempList;
                            if (data instanceof CopyOnWriteArrayList) {
                                tempList = new ArrayList<AnswerRecorder>();
                                if (null != data) {
                                    tempList.addAll(
                                            (ArrayList<AnswerRecorder>) data);
                                }
                            } else {
                                tempList = (ArrayList<AnswerRecorder>) data;
                            }

                            SerializableManager.getInstance().deSerialize(
                                    RepeatKeyUtil.getWordRepeatAnswerListKey(
                                            mDownLoadInfo, mModule, position,
                                            intentWorkId, mUuid),
                                    new BaseCallBack() {
                                        @Override
                                        public void success(Object data) {
                                            try {
                                                ArrayList<WorkAnswers<RepeatAnswerInfo>> answerList;
                                                if (data instanceof CopyOnWriteArrayList) {
                                                    answerList = new ArrayList<WorkAnswers<RepeatAnswerInfo>>();
                                                    if (null != data) {
                                                        answerList.addAll(
                                                                (ArrayList<WorkAnswers<RepeatAnswerInfo>>) data);
                                                    }
                                                } else {
                                                    answerList = (ArrayList<WorkAnswers<RepeatAnswerInfo>>) data;
                                                }

                                                if ((tempList == null
                                                        && answerList == null)
                                                        || (null != answerList
                                                        && tempList != null
                                                        && tempList
                                                        .size() == answerList
                                                        .size())) {
                                                    // 缓存同步再退出
                                                    hideCricleProgress();
                                                    AudioPlayer.getInstance()
                                                            .stop();
                                                    // FileUtils.delete(NSystem.getAnswersMediaPath(uuid));
                                                    finish();
                                                } else {
                                                    mHandler.postDelayed(
                                                            new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                    hideCricleProgress();
                                                                    AudioPlayer
                                                                            .getInstance()
                                                                            .stop();
                                                                    // FileUtils.delete(NSystem.getAnswersMediaPath(uuid));
                                                                    finish();
                                                                }
                                                            }, 3000);

                                                }

                                            } catch (Exception e) {
                                                e.getStackTrace();
                                            }
                                        }

                                        @Override
                                        public void failed(int errorCode,
                                                           Object data) {
                                            failed(data);
                                        }

                                        @Override
                                        public void failed(Object data) {
                                            mHandler.postDelayed(new Runnable() {
                                                @Override
                                                public void run() {
                                                    hideCricleProgress();
                                                    AudioPlayer.getInstance()
                                                            .stop();
                                                    // FileUtils.delete(NSystem.getAnswersMediaPath(uuid));
                                                    finish();
                                                }
                                            }, 3000);
                                        }
                                    });

                        } catch (Exception e) {
                            e.getStackTrace();
                        }
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        failed(data);
                    }

                    @Override
                    public void failed(Object data) {
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                hideCricleProgress();
                                AudioPlayer.getInstance().stop();
                                // FileUtils.delete(NSystem.getAnswersMediaPath(uuid));
                                finish();
                            }
                        }, 3000);
                    }
                });
    }

    /**
     * 刷新显示单词界面
     */
    private void refreshWordUi(int currPoint) {
        if (currPoint >= words.size()) {// 说明已做完
            speechControler.allComplete(false);
            return;
        }
        unitSpeech.setVisibility(View.VISIBLE);
        setNo(speechControler.currentListenAndRepeatIndex + 1, words.size());
        // 第一次进来的时候 刚好已经做完 则显示已经做完

    }

    /**
     * 获取单词
     */
    public void loadWordDetails(final String saveUUid, final int currPoint) {
        // showMiddleProgressBar(getTitleText());
        // String path =
        // ESystem.getPackagesJsonPath(mModule.getResourceList().get(position).getResourceFile());
        // /storage/emulated/0/ciwong/Demo/packages/catalogue_2945_4365_10_4716741214003426081/resource/resource.json
        EpaperDao.getInstance().getSerializableObjects(jsonResourcePath,
                new TypeToken<List<WordDetail>>() {
                }.getType(),
                new BaseExtCallBack(WordReadActivity.this,
                        EApplication.getInstance().getUserInfoBase().getUserId()
                                + "") {

                    @Override
                    public void success(final Object data) {
                        super.success(data);
                        ArrayList<WordDetail> tempWords = (ArrayList<WordDetail>) data;
                        if (!TextUtils.isEmpty(checkedResource)) {
                            // 有选题
                            String[] checkedWords = checkedResource.split(",");
                            words = new ArrayList<WordDetail>();
                            for (String checkedWordId : checkedWords) {
                                WordDetail wd = new WordDetail();
                                wd.setwId(checkedWordId);
                                int index = tempWords.indexOf(wd);
                                if (index != -1) {
                                    words.add(tempWords.get(index));
                                }
                            }
                        } else {
                            words = tempWords;
                        }
                        if (words != null && !words.isEmpty()) {
                            initData(saveUUid);
                            // workLong = CWSys.getSharedInt(getSaveTime(), 0);
                            refreshWordUi(currPoint);
                            if (currPoint < words.size()) {
                                if (isShowHelp) {
                                    // 如果是第一次安装 则要等点完我知道了才能继续
                                    hideCricleProgress();
                                    return;
                                }
                                if (!mIsUnAutoMode) {
                                    // 自动播放
                                    autoPlay(currPoint);
                                } else {
                                    setPlayQuest(words, currPoint);
                                    playOrPause(false, false);
                                }
                            }

                        }
                        hideCricleProgress();
                        // hideMiddleProgressBar();
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                        hideCricleProgress();
                    }

                    @Override
                    public void failed(Object data) {
                        finish();
                        showToastError((int) data);
                        // hideMiddleProgressBar();
                        hideCricleProgress();
                    }
                }

        );
    }

    /**
     * 设置播放语音
     *
     * @param tempWords
     * @param currPoint
     */
    public void setPlayQuest(ArrayList<WordDetail> tempWords, int currPoint) {
        if (currPoint >= 0 && currPoint < tempWords.size()) {
            WordDetail item = tempWords.get(currPoint);
            if (item.getWordFile() != null && !item.getWordFile().equals("")) {
                // 手动模式，显示播放按钮
                read_bottom_view.setPlayState(mIsUnAutoMode, readMode);
            }
        }
    }

    // 倒计时3秒自动开始
    public void autoPlay(final int currPoint) {
        countDownDialog = new CountDownDialog(this, this);
        countDownDialog.setCancelable(false);
        countDownDialog.show();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (countDownDialog != null && countDownDialog.isShowing()) {
                    countDownDialog.dismiss();
                    showTopTip(currPoint);
                }
            }
        }, 3500);
    }

    private void pause() {
        if (!speechControler.isPause()) {
            speechControler.pause();
            switchPauseStateForWord();
        }
    }

    @Override
    public void reStartPlay() {// 切换模式之后 重新开始
        if (speechControler.isPause()
                || speechControler.operateStatus == speechControler.OPERATE_STATUS_STOP) {
            speechControler.startStudy(!mIsUnAutoMode, false);
            // 切换播放按钮状态
            switchPlayState();
            mIsAutoPlayPause = false;
        }
    }

    @Override
    public void playOrPause(boolean isPause, boolean isNeedRecord)// 播放 暂停
    {
        if (isNeedRecord
                && speechControler.operateStatus == speechControler.OPERATE_STATUS_RECORDING) {
            return;
        }
        if (isPause) {
            if (speechControler.operateStatus == speechControler.OPERATE_STATUS_RECORDING) {
                // 正在录音，结束录音
                speechControler.cancelEngine();
            }
        }
        if (speechControler == null) {
            showToastAlert(R.string.initing_yzs);
            return;
        }
        if (mIsPlayRecord && play_dubing_iocn != null) {
            play_dubing_iocn.stopOnlyPlay();
            if (AudioPlayer.getInstance().isPlaying()) {
                AudioPlayer.getInstance().stop();
            }
        }
        isLearn = true;// 是否没有完成学习

        if (!isPause) {
            startTimer();
            speechControler.startStudy(true, false);
            // 切换播放按钮状态
            switchPlayState();
            mIsAutoPlayPause = false;
        } else {
            cancelTimer();
            pause();
            speechControler.operateStatus = speechControler.OPERATE_STATUS_STOP;
            mIsAutoPlayPause = true;
        }
    }

    @Override
    public void onAllComplete(Answer answer,
                              ArrayList<WorkAnswers<RepeatAnswerInfo>> userAnswersList,
                              ArrayList<AnswerRecorder> answerRecorders, String uuid, int score) {
        switchRestartState();
        this.answer = answer;
        this.answer.setActualScore(score);
        answer = getAnswer(answer);
        EJumpManager.jumpToRereadWordResultActivity(R.string.go_back,
                WordReadActivity.this, requirementContent, userAnswersList,
                answerRecorders, words, uuid, answer, mDownLoadInfo, mModule,
                position, mWorkContents, readMode, mRequestCodeFrom, effectiveDate, mIsKaoShiMode, mIsUnAutoMode);
        finish();
    }

    public Answer getAnswer(Answer answer) {// 获取提交答案信息
        try {

            int newWorkLong = (int) (System.currentTimeMillis() - startDate)
                    / 1000;
            int oldWorkLong = CWSys.getSharedInt(getSaveTime(), 0);
            if (newWorkLong < oldWorkLong || newWorkLong < 0) {
                newWorkLong = workLong;
            }
            // 组装提交的答案JSON
            answer.setWorkLong(newWorkLong);
            // 保存一下作业用时
            answer.setWorkId(intentWorkId);
            // 服务id
            answer.setWorkType(mServiceId);
            if (mClassId == null
                    && EApplication.getInstance().getClazz() != null) {
                // 如果classid 没有传进来，用默认的,班级id是必须的，要不然老师端收不到
                mClassId = String
                        .valueOf(EApplication.getInstance().getClazz().getId());
            }

            if (null != mClassId) {
                answer.setClassId(mClassId);
            }
            if (null != userInfo)
                answer.setUserName(userInfo.getRealName());

            answer.setJsonVersion(EConstants.JSON_VERSION);
            answer.setUserAnswer(ESystem.USER_ANSWER);
            answer.setCreateTime(System.currentTimeMillis());
            answer.setBrandId(EApplication.BRAND_ID);

            answer.setVersionId(mVersionId);

            if (null != mDownLoadInfo) {

                if (mDownLoadInfo
                        .getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_OLD) {
                    ModuleContent moduleContent = mModule.getResourceList()
                            .get(position);
                    moduleId = mModule.getModuleInfo().getModuleId();
                    if (mWorkContents != null) {
                        answer.setResourceName(mWorkContents.getResourceName());
                    } else {
                        answer.setResourceName(moduleContent.getResourceName());
                    }
                    // if (null != mVersionId) {
                    // //目前只有单词跟读才会走这里，因为单词跟读资源versionid 有问题
                    //
                    // } else {
                    // answer.setVersionId(moduleContent.getVersionId());
                    // }
                    answer.setParentVersionId(
                            moduleContent.getParentVersionId());
                    answer.setModuleId(moduleId);
                    answer.setResourceType(moduleContent.getResourceType());
                } else {
                    answer.setResourceName(mDownLoadInfo.getResourceName());
                    // if (null != mVersionId) {
                    // //目前只有单词跟读才会走这里，因为单词跟读资源versionid 有问题
                    // answer.setVersionId(mVersionId);
                    // } else {
                    // answer.setVersionId(mDownLoadInfo.getVersionId());
                    // }
                    answer.setParentVersionId("0");
                    answer.setModuleId(moduleId);
                    answer.setResourceType(mDownLoadInfo.getResourceType());
                }
            }
            if (mDownLoadInfo != null) {
                answer.setPackageId(mDownLoadInfo.getBookId());
                answer.setcId(mDownLoadInfo.getChapterId());
            }
            // 暂时先传0 作业内容ID(来源于学生作业记录接口)
            if (mWorkContents == null) {
                answer.setContentId(0);
            } else {
                answer.setContentId(mWorkContents.getContentId());
            }
            answer.setWorkScore(100);// 作业满分分值 暂时先传100
            return answer;
        } catch (Exception e) {
            e.getStackTrace();
        }
        return answer;

    }

    @Override
    public void onComplete() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                int index = speechControler.currentListenAndRepeatIndex + 1;
                index = index > words.size() ? words.size() : index;
                setNo(index, words.size());
            }
        });
    }

    @Override
    public void onListenerComplete() {

    }

    @Override
    public void onSaveRecord(
            ArrayList<WorkAnswers<RepeatAnswerInfo>> userAnswersList,
            ArrayList<AnswerRecorder> answerRecorderList, String saveUuid) {
        Log.d(TAG, "########saveDoWorkRecord saveUuid###########" + saveUuid);
        saveDoWorkRecord(userAnswersList, answerRecorderList, saveUuid,
                words.size());
    }

    @Override
    public void startRecordAnim() {
        read_bottom_view.setRecordState(true, mIsUnAutoMode);// 播放录音动画
    }

    @Override
    public void stopRecordAnim() {
        read_bottom_view.setRecordState(false, mIsUnAutoMode);// 播放录音动画
    }

    @Override
    public void updateProgress(int total, int progress) {// 更新播放进度
        read_bottom_view.setRoundProgressAndMax(total, progress);
    }

    @Override
    public void onSaveSentenceRecord(ArrayList<Sentence> sentenceList) {

    }

    @Override
    public void repeatReadFinsh(AnswerRecorder answerRecorder,
                                EvaluateResult evaluateResult, String yzsAudioUrl) {
        // 重读结束 返回重读结果
        readPeatFished(answerRecorder, evaluateResult, yzsAudioUrl);
    }

    @Override
    public void recError(IOralEvalSDK evalSDK, final SDKError sdkError,
                         IOralEvalSDK.OfflineSDKError offlineSDKError) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                SDKError.Category category = sdkError.category;
                if (mIsUnAutoMode) {
                    next_record.setVisibility(View.VISIBLE);
                }
                if (SDKError.Category.Network == category) {
                    if (!NetworkUtils.isOnline()) {
                        //ToastUtil.INSTANCE.toastCenterNoNetError();
                        ToastUtil.INSTANCE.toastTopError(R.string.connect_disable5);
                    } else {
                        /*ToastUtil.INSTANCE.toastCenterError(
                                "评分过程遇到错误，错误信息：" + sdkError.errno);*/
                        ToastUtil.INSTANCE.toastTopError(getString(R.string.connect_disable7) + "(" + sdkError.errno + ")", Toast.LENGTH_SHORT);
                    }
                } else if (SDKError.Category.Device == category) {
                    DialogUtil.showSettingPermissions(WordReadActivity.this);
                } else {
                    /*ToastUtil.INSTANCE.toastCenterError(
                            "评分过程遇到错误，错误信息：" + sdkError.errno);*/
                    ToastUtil.INSTANCE.toastTopError(getString(R.string.connect_disable7) + "(" + sdkError.errno + ")", Toast.LENGTH_SHORT);
                }
            }
        });
        String logDesc = "云之声评分失败###errorCode####" + sdkError.toString();
        FeedbackUtil.getInstance().addFeedbackLog(
                FeedbackUtil.FEEDBACK_TYPE_EVALUATE, logDesc, "评分失败");
    }

    public void readPeatFished(AnswerRecorder answerRecorder,
                               EvaluateResult evaluateResult, String yzsAudioUrl) {
        Intent intent = new Intent();
        intent.putExtra(IntentFlag.INTENT_FLAG_OBJ,
                (Serializable) answerRecorder);
        intent.putExtra(IntentFlag.INTENT_FLAG_EVALUATE_RESULT,
                (Serializable) evaluateResult);
        intent.putExtra(IntentFlag.INTENT_FLAG_STR, yzsAudioUrl);
        setResult(
                RequestCode.RereadWordResultActivityResquestCode.REPEATE_WORD_REQUEST,
                intent);
        finish();
    }

    /**
     * 文件被删除了
     */
    public void notFile() {
        // String path =
        // ESystem.getPackagesJsonPath(mModule.getResourceList().get(position).getResourceFile());
        File file = new File(jsonResourcePath);
        if (file.exists()) {
            File reParFile = file.getParentFile().getParentFile();
            if (reParFile.exists()) {
                // 递归删除该目录
                ESystem.recurDelete(reParFile);
            }
        }
        this.finish();
    }

    // 123倒计时结束 自动开始做题流程
    @Override
    public void close() {
        playOrPause(false, false);
    }

    public void showTopTip(final int currPoint) {
        if (currPoint > 0 && currPoint <= words.size()) {
            studentRel.setVisibility(View.VISIBLE);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    studentRel.setVisibility(View.GONE);
                }
            }, 2000);
        }
    }

    public IntensiveReadingDialog mIntensiveReadingDialog;

    /**
     * 设置分数
     *
     * @param mAnswerRecorder
     */
    public void setResultScoreStatus(AnswerRecorder mAnswerRecorder) {
        if (mAnswerRecorder != null && mAnswerRecorder.getSoundUrl() != null
                && !mAnswerRecorder.getSoundUrl().equals("")) {
            play_dubing_iocn.setTimeAndPlayBtnState(
                    mAnswerRecorder.getUsetime(), PlayStateView.PLAY_STATUE);
            play_dubing_iocn.setVisibility(View.VISIBLE);
            play_dubing_iocn.setTag(mAnswerRecorder.getSoundUrl());
            next_record.setVisibility(View.VISIBLE);
        } else {
            play_dubing_iocn.setTimeAndPlayBtnState(audioDuration,
                    PlayStateView.PLAY_STATUE);
            play_dubing_iocn.setVisibility(View.GONE);
            next_record.setVisibility(View.GONE);
        }
    }

    /**
     * 进度模式显示UI
     *
     * @param intensiveReadingResultBean
     */
    public void showIntensiveReadingDialog(
            IntensiveReadingResultBean intensiveReadingResultBean) {
        play_dubing_iocn.setTimeAndPlayBtnState(audioDuration,
                PlayStateView.PLAY_STATUE);
        play_dubing_iocn.setVisibility(View.VISIBLE);
        next_record.setVisibility(View.VISIBLE);
        try {
            if (speechControler != null && words != null
                    && speechControler.currentListenAndRepeatIndex >= words
                    .size() - 1) {
                intensiveReadingResultBean.setTheLastWord(true);
            }

            if (mIntensiveReadingDialog == null) {
                mIntensiveReadingDialog = new IntensiveReadingDialog(
                        WordReadActivity.this, intensiveReadingResultBean);
                mIntensiveReadingDialog.setIntensiveReadingClickListener(this);
            } else {
                mIntensiveReadingDialog
                        .setIntensiveReadingResult(intensiveReadingResultBean);
            }
            if (!isFinishing()) {
                mIntensiveReadingDialog.show();
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    private boolean isIntensiveReadingDialogShowing() {
        if (mIntensiveReadingDialog != null
                && mIntensiveReadingDialog.isShowing()) {
            return true;
        }

        return false;
    }

    public void hideIntensiveReadingDialog() {
        if (mIntensiveReadingDialog != null && !isFinishing()) {
            mIntensiveReadingDialog.dismiss();
        }
    }

    // 精读单词页面重读按钮点击
    @Override
    public void onIntensiveReadingClickReread() {
        repeatWord();
    }

    // 精读单词页面下一个按钮点击
    @Override
    public void onIntensiveReadingClickNextWord() {
        nextWord();
    }

    // 精读弹框是点击返回键的回调
    @Override
    public void onIntensiveReadingShowingClickBack() {
        showDailog();
    }

    @Override
    public void nextWord() {
        if (speechControler.operateStatus == speechControler.OPERATE_STATUS_RECORDING) {
            return;
        }
        playOrPause(true, false);
        // 精读模式的下一个逻辑
        // speechControler.scoreViewGone();
        if (words != null
                && speechControler.currentListenAndRepeatIndex >= words.size()) {

            // submit
            speechControler.allComplete(true);
        } else {
            if (mIsUnAutoMode) {
                speechControler.currentListenAndRepeatIndex++;
            }
            speechControler.operateStatus = speechControler.OPERATE_STATUS_PLAYING;
            speechControler.cacheListenAndRepeatIndex = speechControler.currentListenAndRepeatIndex;
            speechControler.playNext();
        }
    }

    @Override
    public void repeatWord() {
        // 精读模式题型重读逻辑
        if (NetworkUtils.isOnline()) {
            speechControler.operateStatus = speechControler.OPERATE_STATUS_PLAYING;
            speechControler.currentListenAndRepeatIndex--;
            speechControler.cacheListenAndRepeatIndex = speechControler.currentListenAndRepeatIndex;
            speechControler.playNext();
        } else {
            ToastUtil.INSTANCE.toastCenterNoNetError();
        }
    }

    @Override
    public void goBackWord() {
        if (speechControler.operateStatus == speechControler.OPERATE_STATUS_RECORDING) {
            return;
        }
        playOrPause(true, false);
        // 精读模式题型上一个
        if (NetworkUtils.isOnline()) {
            if (speechControler.currentListenAndRepeatIndex > 0) {
                speechControler.currentListenAndRepeatIndex--;
                speechControler.operateStatus = speechControler.OPERATE_STATUS_PLAYING;
                speechControler.cacheListenAndRepeatIndex = speechControler.currentListenAndRepeatIndex;
                speechControler.playNext();
                next_record.setVisibility(View.VISIBLE);
            } else {
                ToastUtil.INSTANCE.toastInCenter(WordReadActivity.this,
                        "已经是第一个了");
            }
        } else {
            ToastUtil.INSTANCE.toastCenterNoNetError();
        }
    }

    @Override
    public void complateRecord() {
        // 完成录音
        if (speechControler != null) {
            speechControler.complateRecord();
        }
    }

    @Override
    public void playRecordWord() {
        if (speechControler.operateStatus == speechControler.OPERATE_STATUS_RECORDING) {
            return;
        }
        if (AudioPlayer.getInstance().isPlaying()) {
            AudioPlayer.getInstance().stop();
        }
        if (play_dubing_iocn != null) {
            String soundUrl = (String) play_dubing_iocn.getTag();
            File file = new File(soundUrl);
            if (file == null || !file.exists()) {
                soundUrl = FileUtil.getReNameFilePath(soundUrl);
            }
            AudioPlayer.getInstance().setOnPlayListener(mOnPlayListener)
                    .play(BaseConstants.FILE_PREFIX + soundUrl, true);
        }
    }

    /**
     * 播放录音
     */
    private OnPlayListener mOnPlayListener = new OnPlayListener() {
        @Override
        public void onReadPlayer(long duration, Object mp3) {
            play_dubing_iocn.setTimeAndPlayBtnState(duration,
                    PlayStateView.PLAY_STATUE);
            mIsPlayRecord = true;
        }

        @Override
        public void onPlayStart(Object o) {
            play_dubing_iocn.startPlay();
            mIsPlayRecord = true;
        }

        @Override
        public void stop(Object o) {
            play_dubing_iocn.stopOnlyPlay();
            mIsPlayRecord = false;
        }

        @Override
        public void onError(int i, Object o) {
            play_dubing_iocn.stopOnlyPlay();
            mIsPlayRecord = false;
        }

        @Override
        public void onBuffer(Object o, long l, long l1) {

        }

        @Override
        public void onPlaying(long progress, long max) {

        }
    };

    @Override
    public void recordWord() {
        if (mIsPlayRecord && play_dubing_iocn != null) {
            play_dubing_iocn.stopOnlyPlay();
        }
        if (mIsUnAutoMode) {
            isLearn = true;
            play_dubing_iocn.setVisibility(View.GONE);
            next_record.setVisibility(View.GONE);
        }
        if (speechControler != null) {
            speechControler.hintResultScore();
            speechControler.startStudy(false, true);
        }
    }
}
